#
# Copyright (C) 2008 Erik van Oosten
#
# MIT license.
#

#
# A VirtualAddress represents a single e-mail adres in a Postfix VirtualDomain.
# It has a user-name (the e-mail in the domain) and a redirect. The redirect
# is a comma-separated list of full e-mail addresses.
# Attribute member_of is a list of group names of which the user is a member of.
#
class VirtualAddress < ActiveForm
  include Comparable
  column :user
  column :redirect
  column :member_of_groups
  attr_accessor :user, :redirect, :member_of_groups
  
  validates_presence_of :user, :redirect
  validates_format_of :user, :with => /^[-a-z]+/, :message => "must contain only lowercase and '-'"
  validates_format_of :redirect, :with => /^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name)))(,[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name)))*$/, :message => "is not a  valid e-mail list (comma separated)"

  def initialize(user, redirect, member_of_groups = [])
    @user = user.strip
    @redirect = redirect
    @member_of_groups = member_of_groups
  end

  def VirtualAddress.from_attributes(map)
    VirtualAddress.new(map["user"].strip, map["redirect"].strip, (map["member_of_groups"] || {}).keys)
  end
 
  def update_attributes(map)
    if map
      @redirect = map["redirect"].strip if map.has_key? "redirect"
      if map.has_key? "member_of_groups"
        @member_of_groups = map["member_of_groups"].keys
      else
        @member_of_groups = []
      end
    end
  end

  def <=>(other)
    @user <=> other.user
  end
  
  def member_of_groups
    @member_of_groups || []
  end

  def member_of?(group)
    @member_of_groups && @member_of_groups.include?(group)
  end

  def add_to_group(group)
    if @member_of_groups
      @member_of_groups << group unless member_of?(group)
    else
      @member_of_groups = [group]
    end
    nil
  end

  def remove_from_group(group)
    @member_of_groups.delete(group) if @member_of_groups
    nil
  end
  
end
